<?php
    /*
     * /web/TianShenDai/dev.msg.tianshenjr.com/public/index.php /console/excutePushToNoOrderCustomer/page/aa/pageLimit/1
     */
    header('content-type:text/html;charset=utf-8' );
    date_default_timezone_set('PRC'); //设置中国时区
    try {
        $pdo = new PDO("mysql:host=127.0.0.1;dbname=tianshendai_message", "root", "tianshen502#1301$");
        
//        $pdo = new PDO("mysql:host=rm-m5ej125a7585jxw8d.mysql.rds.aliyuncs.com;dbname=tianshendai_pro", "tianshendb_root", "t*4DB&6$#Sd0@3");
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        
        
    }
    $pdo->query("set names utf8");
    
    
    $startMinute=1507802760;//strtotime(date('YmdHi'.'00',strtotime('-1 Minute')));
    $endMinute=strtotime(date('YmdHi'.'59',strtotime('+1 Minute')));
    
    $sql="
      select 
        id,target_user,add_time
      from 
        message_box 
      where 
        status=2 
      and 
        is_release=0 
      and 
        release_time>={$startMinute} 
      and 
        release_time<={$endMinute}
    ";
    
    $data=$pdo->query($sql);
    if(empty($data)){
        exit('no message to send !');
    }
    
    foreach ($data as $k => $v){
        $pageNum=0;
        //1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户
        if($v['target_user']==1){//全部用户
            $count=getPageNumByPushToAllCustomer();
            
            $pageLimit=10000;
            $pageNum=ceil($count/$pageLimit);
            $manyCmd=[];
            for ($i=1;$i<=$pageNum;$i++){
                $oneCmd=[
                    '/data/wwwroot/dev.msg.tianshenjr.com/think',
                    'PushToAll',
                    $i,
                    $pageLimit,
                    $v['id'],
                    $v['add_time']
                ];
                $manyCmd[]=$oneCmd;
            }
            excuteCommond($manyCmd,$v['id']);
            
        }
        if($v['target_user']==2){//未下单用户
            $count=pushToNoOrderCustomer();
            $pageLimit=10000;
            $pageNum=ceil($count/$pageLimit);
            $manyCmd=[];
            for ($i=1;$i<=$pageNum;$i++){
                $oneCmd=[
                    '/web/TianShenDai/dev.msg.tianshenjr.com/think',
                    'PushToNoOrder',
                    $i,
                    $pageLimit,
                    $v['id'],
                    $v['add_time']
                ];
                $manyCmd[]=$oneCmd;
            }
            excuteCommond($manyCmd,$v['id']);
        }
        if($v['target_user']==3){//3:还款中用户
            $count=getPageNumByPushToInRepayment();
            $pageLimit=10000;
            $pageNum=ceil($count/$pageLimit);
            $manyCmd=[];
            for ($i=1;$i<=$pageNum;$i++){
                $oneCmd=[
                    '/web/TianShenDai/dev.msg.tianshenjr.com/think',
                    'InRepayment',
                    $i,
                    $pageLimit,
                    $v['id'],
                    $v['add_time']
                ];
                $manyCmd[]=$oneCmd;
            }
            excuteCommond($manyCmd,$v['id']);
        }
        if($v['target_user']==4){//4:已逾期用户
            $count=getPageNumByPushToOverdue();
            $pageLimit=10000;
            $pageNum=ceil($count/$pageLimit);
            $manyCmd=[];
            for ($i=1;$i<=$pageNum;$i++){
                $oneCmd=[
                    '/web/TianShenDai/dev.msg.tianshenjr.com/think',
                    'Overdue',
                    $i,
                    $pageLimit,
                    $v['id'],
                    $v['add_time']
                ];
                $manyCmd[]=$oneCmd;
            }
            excuteCommond($manyCmd,$v['id']);
        }
        if($v['target_user']==5){//5:指定用户,此种类型很少，暂时不开启子进程
            $count=getPageNumByPushToInRepayment();
            $pageLimit=10000;
            $pageNum=ceil($count/$pageLimit);
            $manyCmd=[];
            for ($i=1;$i<=$pageNum;$i++){
                $oneCmd=[
                    '/web/TianShenDai/dev.msg.tianshenjr.com/think',
                    'InRepayment',
                    $i,
                    $pageLimit,
                    $v['id'],
                    $v['add_time']
                ];
                $manyCmd[]=$oneCmd;
            }
            excuteCommond($manyCmd,$v['id']);
        }
        
    }
    
    
    function excuteCommond($cmdArr,$msgID){
        $file = "/web/TianShenDai/test/{$msgID}.log";
        $file2 = "/web/TianShenDai/test/{$msgID}".'info'.".log";
        /*$a=array (
            0 => '/data/wwwroot/dev.msg.tianshenjr.com/think',
            1 => 'PushToAll',
            2 => 1,
            3 => 10000,
            4 => '130',
            5 => '1507802770',
        );
    
        $res = pcntl_exec('/usr/bin/php', $a);*/
        $is_main_process = true;
        if(!empty($cmdArr)){
            $p_list=[];
            foreach ($cmdArr as $v){
                $p = pcntl_fork();
                if ($p === -1) {
                    exit('create process ' . json_encode($v)  ."<>$msgID<>". ' failed!' . PHP_EOL);
                } else if ($p === 0) {
                    $is_main_process = false;
                    // 每批次插入开始时间
                    $s_time = microtime(true);

                    $res = pcntl_exec('/usr/bin/php', $v);
                    // 每批次插入结束时间
                    $e_time = microtime(true);
                    // 每批次插入耗费的时间
                    $duration = $e_time - $s_time;
                    // 输出信息
                    $info='插入批次 ' . json_encode($v) ."<>$msgID<>". ' 花费时间： ' . $duration . 's' . PHP_EOL;
                    $fs2 = fopen($file2 , 'a');
                    fwrite($fs2 ,$info . PHP_EOL);
                    fclose($fs2);
                    
                    // 记录每次插入耗时（用于统计总耗时）
                    $fs = fopen($file , 'a');
                    fwrite($fs ,$duration . "\r\n");
                    fclose($fs);
        
                    break;
                } else {
                    $p_list[] = $p;
                }
            }
    
    
            if ($is_main_process) {
                foreach ($p_list as $c_pid)
                {
                    pcntl_waitpid($c_pid , $status);
                }
        
        
        
                $fs = fopen($file , 'r') or exit('process ' . json_encode($v)."<>$msgID<>" . ' open the file failed!' . PHP_EOL);
                $total_time = 0;
        
                while ($line = fgets($fs))
                {
                    $line = str_replace("\r\n" , '' , $line);
                    $line = floatval($line);
            
                    $total_time += $line;
                }
        
                echo count($cmdArr) . ' 条进程 耗时：' . $total_time . ' s ' .  PHP_EOL;
        
            }
        }
    }
    
    /*
     * 计算全部用户类型的jpush数量
     */
    function getPageNumByPushToAllCustomer(){
        try {
            $pdo = new PDO("mysql:host=127.0.0.1;dbname=tianshendb_dev", "root", "root");
            //        $pdo = new PDO("mysql:host=rm-m5ej125a7585jxw8d.mysql.rds.aliyuncs.com;dbname=tianshendai_pro", "tianshendb_root", "t*4DB&6$#Sd0@3");
        } catch (PDOException $e) {
            exit('Connection failed: ' . $e->getMessage());
        }
        $sql='select count(id) as count from customer where push_id!=""';
        $data=$pdo->query($sql);
        if(empty($data)){
            exit('no data to send ');
        }
        $count=0;
        foreach ($data as $v){
            $count=$v['count'];
        }
        return $count;
    }
    
    /*
     * 计算未成功下单的jpush数量
     */
    function getPageNumByPushToNoOrderCustomer(){
        try {
            $pdo = new PDO("mysql:host=127.0.0.1;dbname=tianshendai_dev", "root", "root");
            //        $pdo = new PDO("mysql:host=rm-m5ej125a7585jxw8d.mysql.rds.aliyuncs.com;dbname=tianshendai_pro", "tianshendb_root", "t*4DB&6$#Sd0@3");
        } catch (PDOException $e) {
            exit('Connection failed: ' . $e->getMessage());
        }
        $sql='
        SELECT
            count(customer.id) as count
        FROM
            customer
        WHERE
            customer.push_id != ""
        AND id NOT IN(
            SELECT
                customer_id
            FROM
                consume_history
            WHERE
                (
                    `status` = 3
                    OR `status` = 8
                    OR `status` = 12
                    OR `status` = 7
                )
            GROUP BY
                customer_id
        ) 
        ';
        $data=$pdo->query($sql);
        if(empty($data)){
            exit('no data to send ');
        }
        $count=0;
        foreach ($data as $v){
            $count=$v['count'];
        }
        return $count;
    }
    
    /*
     * 计算处于还款中的jpush数量
     */
    function getPageNumByPushToInRepayment(){
        try {
            $pdo = new PDO("mysql:host=127.0.0.1;dbname=tianshendai_dev", "root", "root");
            //        $pdo = new PDO("mysql:host=rm-m5ej125a7585jxw8d.mysql.rds.aliyuncs.com;dbname=tianshendai_pro", "tianshendb_root", "t*4DB&6$#Sd0@3");
        } catch (PDOException $e) {
            exit('Connection failed: ' . $e->getMessage());
        }
        $sql='
        SELECT COUNT(*) AS count FROM (
            SELECT
                id
            FROM
                consume_history
            WHERE
                `status` = 8
            GROUP BY
                customer_id
            ORDER BY id DESC
        ) a
        ';
        $data=$pdo->query($sql);
        if(empty($data)){
            exit('no data to send ');
        }
        $count=0;
        foreach ($data as $v){
            $count=$v['count'];
        }
        return $count;
    }
    //getPageNumByPushToOverdue
    /*
         * 计算处于还款中的jpush数量
         */
    function getPageNumByPushToOverdue(){
        try {
            $pdo = new PDO("mysql:host=127.0.0.1;dbname=tianshendai_dev", "root", "root");
            //        $pdo = new PDO("mysql:host=rm-m5ej125a7585jxw8d.mysql.rds.aliyuncs.com;dbname=tianshendai_pro", "tianshendb_root", "t*4DB&6$#Sd0@3");
        } catch (PDOException $e) {
            exit('Connection failed: ' . $e->getMessage());
        }
        $sql='
        SELECT COUNT(*) AS count FROM (
            SELECT
                consume_installment_history.id
            FROM
                consume_installment_history
            LEFT JOIN consume_history ON consume_history.id=consume_installment_history.parent_id
            WHERE
                consume_installment_history.`repayment_time` < now()
            AND 
                consume_installment_history.status=0
            GROUP BY
                consume_installment_history.parent_id
        ) as a 
        ';
        $data=$pdo->query($sql);
        if(empty($data)){
            exit('no data to send ');
        }
        $count=0;
        foreach ($data as $v){
            $count=$v['count'];
        }
        return $count;
    }
    